<?php
/**
 * Copyright (c) 2013 pipapai.com
 */
JLoader::register('PResumesModelResumes', OC::$SERVERROOT."/apps/resumes/lib/resumes.php");
JLoader::register('PResumesModelResume', OC::$SERVERROOT."/apps/resumes/lib/resume.php");
JLoader::register('PResumesModelSearch', OC::$SERVERROOT."/apps/resumes/lib/search.php");
JLoader::register('PResumesModelSearchResume', OC::$SERVERROOT."/apps/resumes/lib/searchresume.php");
JLoader::register('PResumesHelper', OC::$SERVERROOT."/apps/resumes/lib/helper.php");
JLoader::register("PCompanyHelper", OC::$SERVERROOT."/apps/company/lib/helper.php");
JLoader::register("PCalendarModellistview", OC::$SERVERROOT."/apps/calendar/lib/listview.php");
JLoader::register("PCalendarHelper", OC::$SERVERROOT."/apps/calendar/lib/helper.php");
JLoader::register("PCompanyModelThirdAccounts", OC::$SERVERROOT."/apps/company/lib/thirdaccounts.php");
JLoader::register('ProvinceHelper', JPATH_SITE.'/components/com_city/helper.php');

class PSearchController {
   public static function offsitesearch() {
      if(!PUtil::checkUserLogin(true))
         return; 

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      // Get offsite tab
      $tab = isset($_COOKIE['tab']) ? $_COOKIE['tab'] : '';
      $chosen_site = isset($_COOKIE['chosen_site']) ? explode(',', $_COOKIE['chosen_site']) : array();
      $search_tid = isset($_COOKIE['offsetsearch_tid']) ? intval($_COOKIE['offsetsearch_tid']) : 0;

      $app = PFactory::getApplication();

      // Get syncto
      $syncto = $app->getUserState('search_syncto', '');
      // Only pop up the first time
      $app->setUserState('search_syncto','');

      $model = new PResumesModelResumes();
      $search_model = new PResumesModelSearch();
      $thirdModel = new PCompanyModelThirdAccounts();

      // Catch termid from different places
      $term_id = JRequest::getInt('tid', 0);
      $source = array_filter(explode(",", JRequest::getString('source', ''))); 
      $job_id = JRequest::getInt('jobid',0);
      $newsearch = JRequest::getInt('new',0);
      $newsearch = $term_id ? false : $newsearch; # if term_id is given, newsearch will be false 
      $term_id = ($term_id || $newsearch) ? $term_id : $search_tid; # only use cookie search_tid when term_id is not given and newsearch is false 

      $search_info = array(); 
      if(!$newsearch) { 
         $search_info = $search_model->getSearchInfo($term_id);
      }

      // if search_info is null, term_id must be 0 
      if(empty($search_info)) {
         $term_id = 0;   
      }

      $last_sync_result = isset($search_info['last_sync_result']) ? $search_info['last_sync_result'] : array();
      $nterm_id = !empty($search_info['id']) ? $search_info['id'] : 0;
      $terms = array();
      if(!empty($nterm_id)) {
         // we got a valid last search term. if term_id is not given, redirect it have tid parameter 
         if(!$term_id) {
            OC_Response::redirect(OC_Helper::linkToRoute('resumes_offsitesearch',array('tid'=>$nterm_id)));
            return; 
         }

         $term_id = $nterm_id; 
         $terms = empty($search_info['terms']) ? array() : $search_info['terms'];
      }

      // Get search info
      $jobterms = array(); 
      if($job_id) {
         // if source is empty, take source from terms saved source 
         if(empty($source)) {
            $source = isset($terms['source']) ? $terms['source'] : array();
         }

         $jobterms = $search_model->getTermsByJobid($job_id, $source);
         $terms = array_merge($jobterms, $terms); 
      } 

      $offsite_list = array();
      if (!empty($term_id)) {
         $offsite_list = $search_model->getSearchResult($term_id, $last_sync_result);
      }

      // Get third account stats
      $sync_info = $thirdModel->getCompanyThirdToolsInfo();
      $account_info = $sync_info['login'] ? json_decode($sync_info['login'],true) : array();

      // Do internal search
      $resumes = array();
      $resumeStatuses = PResumesHelper::getResumeStatuses();
      $permissions = "";
      $pagination = "";
      $searchUrl = "";
      $token = "";
      $resumedir = $app->getUserState('resumedir', null);
      if (!empty($terms['pipapai'])) {
         if (PCompanyHelper::isJobManager() && !PCompanyHelper::isJobManagerViewOnly()) {
            $permissions = OCP\PERMISSION_READ;
            $permissions |= OCP\PERMISSION_CREATE;
            $permissions |= OCP\PERMISSION_UPDATE;
            $permissions |= OCP\PERMISSION_DELETE;
            $permissions |= OCP\PERMISSION_SHARE;
         } else {
            // default to read permission
            $permissions = OCP\PERMISSION_READ;
            $permissions |= OCP\PERMISSION_SHARE;
         }

         $nterms = $terms;
         unset($nterms['source']);
         unset($nterms['pipapai']);
         unset($nterms['51job']);
         unset($nterms['zhilian']);
         unset($nterms['jiancai']);
         list($resumes, $pagination, $token) = $model->getList('-1', 0, $nterms);

         // Internal search result part.list
         $internallist = new OCP\Template('resumes', 'part.list', '');
         $internallist->assign('resumes', $resumes);
         $internallist->assign('baseURL', OCP\Util::linkToRoute('resumes_index'));
         $internallist->assign('viewURL', OCP\Util::linkToRoute('resume_view', array('id' => '')));
         $internallist->assign('downloadURL', OCP\Util::linkToRoute('resume_download', array('resume' => '/')));
         $internallist->assign('disableSharing', false);
         $internallist->assign('searchtoken', $token);
      }

      // Offsite search result part.list
      $offsitelist = new OCP\Template('resumes', 'part.offsite.list', '');
      $offsitelist->assign('baseURL', OCP\Util::linkToRoute('resumes_offsitesearch'));
      $offsitelist->assign('viewURL', OCP\Util::linkToRoute('resume_offsiteresume', array('id' => '')));
      $offsitelist->assign('tab', $tab);
      $offsitelist->assign('terms', $terms);
      $offsitelist->assign('term_id', $term_id);
      $offsitelist->assign('last_sync_result', $last_sync_result);
      $offsitelist->assign('offsite_list', $offsite_list);
      $offsitelist->assign('showsearchresumedetails', JArrayHelper::getValue($resumedir, 'showsearchresumedetails', 0));

      // offiset search terms html 
      $offsiteterm = new OCP\Template('resumes', 'part.offsite.term', '');
      $offsiteterm->assign('terms', $terms);

      // Offsite main page
      $tmpl = new OCP\Template('resumes', 'offsitesearch', 'user');
      $tmpl->assign('page_title', '第三方搜索');
      $tmpl->assign('terms', $terms);
      $tmpl->assign('accounts', array_keys($account_info));
      $tmpl->assign('tab', $tab);
      $tmpl->assign('chosen_site', $chosen_site);
      $tmpl->assign('term_id', $term_id);
      $tmpl->assign('last_sync_result', $last_sync_result);
      $tmpl->assign('syncto', empty($syncto) ? '' : $syncto);
      $tmpl->assign('offsitelist', $offsitelist->fetchPage());
      $tmpl->assign('searchterms', $offsiteterm->fetchPage());
      // For internal search use
      $tmpl->assign('allowZipDownload', intval(OCP\Config::getSystemValue('allowZipDownload', true)));
      $tmpl->assign('downloadURL', OCP\Util::linkToRoute('resume_download', array('resume' => '/')));
      $tmpl->assign('disableSharing', false);
      $tmpl->assign('resumes', $resumes);
      $tmpl->assign('resumeStatuses', $resumeStatuses);
      $tmpl->assign('permissions', $permissions);
      $tmpl->assign('pagination', $pagination);
      $tmpl->assign('orderBy', JArrayHelper::getValue($resumedir, 'orderby', 'added'));
      $tmpl->assign('orderDir', strtolower(JArrayHelper::getValue($resumedir, 'orderdir', 'desc')));
      $tmpl->assign('topnlist', JRequest::getInt('topnlist', 0));
      $tmpl->assign('searchtoken', $token);
      $tmpl->assign('showsearchresumedetails', JArrayHelper::getValue($resumedir, 'showsearchresumedetails', 0));
      if (!empty($terms['pipapai'])) {
         $tmpl->assign('internallist', $internallist->fetchPage());
      }
      $tmpl->printPage();
   }

   public static function setSearchTerms() {
      OC_JSON::setContentTypeHeader();

      $model = new PResumesModelSearch();
      $result = $model->setSearchTerms();
      if ( !$result ) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess($result, null, null, false));
   }

   public static function offsiteresume() {
      if(!PUtil::checkUserLogin(true))
         return;

      $app = PFactory::getApplication();
      $companyid = 0;

      if (PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_login"));
         return;
      } else {
         $user = PFactory::getMasterUser();
         $companyid = $user->id;
      }

      $resumeid = JRequest::getInt('id', 0);
      if(empty($resumeid))
         return true;

      $model = new PResumesModelSearchResume();
      $info = $model->getSearchResultByID($resumeid,$companyid);

      if(empty($info)) {
         $tmpl = new OC_Template('', '404', 'user');
         $tmpl->assign('error', '简历未找到');
         $tmpl->printPage();
         return;
      }

      // Update resume's is_viewed
      $model->updateResumeIsViewed($info,$companyid);

      $tmpl = new OCP\Template('resumes', 'offsiteresume', 'user');
      $tmpl->assign('info', $info);
      $tmpl->assign('page_title', '第三方简历详情');
      $tmpl->printPage();
   }

   public static function hide() {
      if(!OC_User::isLoggedIn()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_login"));
         return;
      }
      $model = new PResumesModelSearchResume();
      if(!$model->hide()) {
         OCP\JSON::error(array('error' => $model->getError()));
         return false;
      }

      return true;
   }

   public static function show() {
      if(!OC_User::isLoggedIn()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_login"));
         return;
      }
      $model = new PResumesModelSearchResume();
      if(!$model->hide(1)) {
         OCP\JSON::error(array('error' => $model->getError()));
         return false;
      }

      return true;
   }


}
